<script lang="ts" setup>
import * as echarts from 'echarts/core'
import i18n from '@/i18n'
import {
  GridComponent,
  TitleComponent,
  TooltipComponent,
  type GridComponentOption
} from 'echarts/components'
import { LineChart, type LineSeriesOption } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted, ref } from 'vue'
import { getChartsDataAPI } from '@/api/home'
import type { ChartsData, ItemData } from '@/interface'
import { formatDate } from '@/utils/format'
import dayjs from 'dayjs'

const { t } = i18n.global

echarts.use([
  GridComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  TitleComponent,
  TooltipComponent
])

type EChartsOption = echarts.ComposeOption<
  GridComponentOption | LineSeriesOption
>

const userDataTime = ref({
  earliestTime: new Date(),
  latestTime: new Date()
})
const questionDataTime = ref({
  earliestTime: '',
  latestTime: ''
})
const chartsData = ref({
  questionDataTime: '',
  userDataTime: ''
})
const getChartsData = async () => {
  const { data: res } = await getChartsDataAPI(chartsData.value)
  if (res?.status === 200) {
    handleChartsData(res.data)
  }
}

// 数据处理
const handleChartsData = (data: ChartsData) => {
  // 补全 userData
  const d = chartsData.value.userDataTime
    ? dayjs(
        `${new Date(chartsData.value.userDataTime).getFullYear}-${new Date(chartsData.value.userDataTime).getMonth() + 1}-01`
      ).daysInMonth()
    : new Date().getDate()
  data.days.forEach((day: number) => {
    if (day <= d) {
      const found = data.userData.find((item) => parseInt(item.name) === day)
      if (!found) {
        data.userData.push({ name: `${day}日`, value: '0' })
      }
    }
  })

  data.userData.sort(
    (a: ItemData, b: ItemData) => parseInt(a.name) - parseInt(b.name)
  )

  // 处理时间戳
  userDataTime.value.earliestTime = new Date(data.userDataTime.earliestTime)
  userDataTime.value.latestTime = new Date(data.userDataTime.latestTime)

  questionDataTime.value.earliestTime = formatDate(
    data.questionDataTime.earliestTime,
    'YYYY'
  )
  questionDataTime.value.latestTime = formatDate(
    data.questionDataTime.latestTime,
    'YYYY'
  )

  // 补全 questionData
  const allMonths = Array.from(
    {
      length: chartsData.value.questionDataTime ? 12 : new Date().getMonth() + 1
    },
    (_, i) => String(i + 1).padStart(2, '0')
  )

  allMonths.forEach((month: string) => {
    const found = data.questionData.find((item: ItemData) => {
      return parseInt(item.name) === parseInt(month)
    })

    if (!found) {
      data.questionData.push({ name: `${+month}月`, value: '0' })
    }
  })

  data.questionData.sort((a, b) => parseInt(a.name) - parseInt(b.name)) // 按月份排序

  getCharts(data)
}

// 生成ECharts
const getCharts = (data: ChartsData) => {
  const userOption: EChartsOption = {
    title: {
      left: 'center',
      text: t('HOME.USER_ACTIiVICT')
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: data.days
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: (value) => {
        return Math.floor(value.max)
      },
      minInterval: 1
    },
    series: [
      {
        data: data.userData,
        type: 'line'
      }
    ]
  }
  const user = document.getElementById('user')!
  const userChart = echarts.init(user)
  userOption && userChart.setOption(userOption)

  const timu = document.getElementById('timu')!
  const timuChart = echarts.init(timu)
  const timuOption: EChartsOption = {
    title: {
      left: 'center',
      text: t('HOME.QUESTION_MONTH_COUNT')
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: [
        '01',
        '02',
        '03',
        '04',
        '05',
        '06',
        '07',
        '08',
        '09',
        '10',
        '11',
        '12'
      ]
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: (value) => {
        return Math.floor(value.max)
      },
      minInterval: 1
    },
    series: [
      {
        data: data.questionData,
        type: 'line'
      }
    ]
  }
  timuOption && timuChart.setOption(timuOption)
}

onMounted(() => {
  getChartsData()
})

// 处理用户活跃度禁用月份
const handleDisabledMonth = (date: Date) => {
  const year = date.getFullYear() // 当前年份
  const month = date.getMonth() + 1 // 当前月份

  const earliestYear = userDataTime.value.earliestTime.getFullYear() // 最早年份
  const latestYear = userDataTime.value.latestTime.getFullYear() // 最晚年份
  const earliestMonth = userDataTime.value.earliestTime.getMonth() + 1 // 最早月份
  const latestMonth = userDataTime.value.latestTime.getMonth() + 1 // 最晚月份

  if (year < earliestYear || year > latestYear) {
    return true
  }

  if (year !== earliestYear && (month < earliestMonth || month > latestMonth)) {
    return true
  }
}
// 处理题目禁用年份
const handleDisabledYear = (year: Date) => {
  return (
    year.getFullYear() > +questionDataTime.value.latestTime ||
    year.getFullYear() < +questionDataTime.value.earliestTime
  )
}
</script>

<template>
  <div class="charts-container">
    <div class="charts-user-box">
      <el-date-picker
        class="charts-user-picker"
        v-model="chartsData.userDataTime"
        type="month"
        placeholder="请选择月份"
        :disabled-date="handleDisabledMonth"
        @change="getChartsData()"
      />
      <div class="charts-user" id="user"></div>
    </div>
    <div class="charts-timu-box">
      <el-date-picker
        class="charts-user-picker"
        v-model="chartsData.questionDataTime"
        type="year"
        placeholder="请选择年份"
        :disabled-date="handleDisabledYear"
        @change="getChartsData"
      />
      <div class="charts-timu" id="timu"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.charts-container {
  .charts-user-box,
  .charts-timu-box {
    display: flex;
    flex-direction: column;
    align-items: end;
    :deep(.charts-user-picker) {
      margin-right: 200px;
    }
    .charts-user {
      width: 100%;
      height: 600px;
      margin-bottom: 20px;
    }
  }
  .charts-timu {
    width: 100%;
    height: 600px;
  }
}
</style>
